import React, { useReducer } from "react";

// defaultState要表示全局仓库的数据
const defaultState = {
  count: 10,
  name: "zhangsan",
};

// reducer就是用来改变仓库的方法
// reducer只能是纯函数
const reducer = (state, action) => {
  // action带有type属性的对象
  switch (action.type) {
    case "add":
      return {
        ...state,
        count: state.count + 1,
      };
    case "minus":
      return {
        ...state,
        count: state.count - 1,
      };
    default:
      return state;
  }
};

const App = () => {
  // state就是仓库数据
  // dispatch就是调用以后触发reducer
  // dispatch里面传的对象就是reducer函数接收的action
  const [state, dispatch] = useReducer(reducer, defaultState);
  return (
    <>
      <h2>useReducer</h2>
      <p>count: {state.count}</p>
      <button onClick={() => dispatch({ type: "add" })}>btn</button>
    </>
  );
};

export default App;
